package xyz.xtgl.security.springboot.controller;

import xyz.xtgl.security.springboot.entity.CustomUserDetails;
import common.core.util.CommonUtil;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author liubo
 * @created 2019-12-13 17:15
 */
@RestController
public class LoginController {



    @RequestMapping(path = "/login-success" , produces = {"text/plain;charset:UTF-8"})
    public Object loginSuccess(){
        return "登录成功";
    }

    @PreAuthorize("hasAnyAuthority('p1')")
    @GetMapping(path = "/r/r1" , produces = {"text/plain;charset:UTF-8"})
    public Object r1(){
        return getUsername()+"访问资源1";
    }

    @PreAuthorize("hasAnyAuthority('p2')")
    @GetMapping(path = "/r/r2" , produces = {"text/plain;charset:UTF-8"})
    public Object r2(){
        return "访问资源2";
    }

    @PreAuthorize("hasAnyAuthority('p3')")
    @GetMapping(path = "/r/r3" , produces = {"text/plain;charset:UTF-8"})
    public Object r3(){
        return "访问资源3";
    }

    private String getUsername(){
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if(CommonUtil.isEmpty(authentication)){
            return "匿名";
        }
        return ((CustomUserDetails)authentication.getPrincipal()).getUsername();
    }

}
